package com.qiwenshare.file.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiwenshare.file.component.InitData;
import com.qiwenshare.file.domain.Department;
import com.qiwenshare.file.mapper.JobMapper;
import com.qiwenshare.file.domain.Job;
import com.qiwenshare.file.api.JobService;
import com.qiwenshare.file.util.SpringBeanUtil;
import com.qiwenshare.file.vo.department.DepartmentTreeVo;
import com.qiwenshare.file.vo.job.JobTreeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 职位表(Job)表服务实现类
 *
 * @author makejava
 * @since 2023-09-25 19:45:39
 */
@Service("jobService")
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {

    @Autowired
    private JobMapper jobMapper;

    @Override
    public List<JobTreeVo> selectJobTree() {
        List<Job> jobList = jobMapper.selectList(new QueryWrapper<>());
        List<JobTreeVo> treeList = new ArrayList<>();
        for (Job job : jobList) {
            if (StringUtils.isBlank(job.getParentJobId())) {
                JobTreeVo jobTreeVo = SpringBeanUtil.copyProperties(job, JobTreeVo.class);
                jobTreeVo.setTitle(jobTreeVo.getJobName());
                jobTreeVo.setValue(jobTreeVo.getJobId());
                treeList.add(jobTreeVo);
            }
        }
        generateTree(jobList, treeList);
        return treeList;
    }

    @Override
    public List<Job> selectList() {
        return jobMapper.selectList(new QueryWrapper<>());
    }

    private void generateTree(List<Job> jobList, List<JobTreeVo> treeList) {
        for (JobTreeVo treeVo : treeList) {
            List<JobTreeVo> children = new ArrayList<>();
            for (Job job : jobList) {
                if (treeVo.getJobId().equals(job.getParentJobId())) {
                    JobTreeVo vo = SpringBeanUtil.copyProperties(job, JobTreeVo.class);
                    vo.setTitle(vo.getJobName());
                    vo.setValue(vo.getJobId());
                    children.add(vo);
                }
            }
            treeVo.setChildren(children);
            if (CollectionUtil.isNotEmpty(children)) {
                generateTree(jobList, treeVo.getChildren());
            }

        }
    }
}

